<?php
  define('SQL_LOG_DIR', 'sql_logs');

  class db_mysql {
    private $host;		  #	私有属性主机名
    private $user;		  #	私有属性数据库登录名
    private $pass;		  #	私有属性数据库登录密码
    private $database;	#	私有属性数据库名
    private $debug;
    private $logfile;

    public $codepage;
    public $link;		  #	私有属性数据库连接
    public $lastcost;

    public $errno;
    public $error;

    public $SQL;        # 上次执行的SQL
   /**
    *	构造函数,初始化属性值.
    **/
    public function __construct($host, $user, $pass, $db, $codepage = NULL, $debug = FALSE)
    {
      $this->host = $host;
      $this->user = $user;
      $this->pass = $pass;
      $this->database = $db;
      $this->codepage = $codepage;
      $this->debug = $debug;
      $this->logfile = SQL_LOG_DIR . DIRECTORY_SEPARATOR . basename($_SERVER['SCRIPT_NAME'], '.php') . '.sql';
      $this->link = FALSE;
      $this->lastcost = 0;

      if($this->debug){
        $time_begin = microtime(true);
      }

      if($link = mysqli_connect($this->host, $this->user, $this->pass, $this->database)){
        if(empty($this->codepage)){
          $rs = mysqli_query($link, "SHOW VARIABLES LIKE 'character_set_database'");
          $row = mysqli_fetch_assoc($rs);
          mysqli_free_result($rs);
          $this->codepage = $row['Value'];
        }
        mysqli_set_charset($link, $this->codepage);

        $this->link = $link;
      }else{
        $this->errno = mysqli_connect_errno();
        $this->error = 'Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error();
      }

      if($this->debug){
        $this->lastcost = microtime(true) - $time_begin;
      }
    }

    /**
    *	连接数据库方法.
    **/
    public function query($SQL)
    {
      if(empty($this->link)) return FALSE;

      if($this->debug){
        $time_begin = microtime(true);
      }
      $this->SQL = $SQL;
      if($this->debug){
        file_put_contents($this->logfile, '-- [' . date("Y-m-d H:i:s") . ']:' . PHP_EOL . print_r($SQL, true) . PHP_EOL, FILE_APPEND);
      }
      if($this->codepage != 'utf8') $SQL = iconv('UTF-8', 'GBK', $SQL);
      $rs = mysqli_query($this->link, $SQL);
      if($rs === FALSE){
        $this->errno = mysqli_errno($this->link);
        $this->error = mysqli_error($this->link);

        if($this->debug){
          file_put_contents($this->logfile, '-- SQL错误：[' . $this->errno . '] ' . $this->error . PHP_EOL . PHP_EOL, FILE_APPEND);
        }
      }else{
        if($this->debug){
          $this->lastcost = microtime(true) - $time_begin;
          if(is_object($rs)){
            file_put_contents($this->logfile, '-- 返回记录数：' . mysqli_num_rows($rs) . '条，耗时：' . number_format($this->lastcost,6) . '秒。' . PHP_EOL . PHP_EOL, FILE_APPEND);
          }else{
            file_put_contents($this->logfile, '-- 受影响记录数：' . mysqli_affected_rows($this->link) . '条，耗时：' . number_format($this->lastcost,6) . '秒。' . PHP_EOL . PHP_EOL, FILE_APPEND);
          }
        }
      }

      return $rs;
    }

    public function insert($table, $data = FALSE, $extra_sql = NULL)
    {
      if(empty($data)){
        return $this->query($table);
      }

      if(is_array($data)){
        if(array_depth($data) == 1 && is_assoc_array($data)){
          $key_value_pairs = array();
          foreach($data as $key => $value){
            $key_value_pairs[] = "{$key}='{$value}'";
          }
          $SQL = "INSERT INTO {$table} SET " . implode(', ', $key_value_pairs);
          if(!empty($extra_sql)){
            $SQL .= ", {$extra_sql}";
          }
          return $this->query($SQL);
        }
        if(array_depth($data) == 2 && is_indexed_array($data)){
          foreach($data as $row){
            if(!is_assoc_array($row)){
              return FALSE;
            }
          }
          foreach($data as $row){
            if($this->insert($table, $row, $extra_sql) === FALSE){
              return FALSE;
            }
          }
          return TRUE;
        }
      }
      return FALSE;
    }

    public function update($table, $data = FALSE, $condition = FALSE)
    {
      if(empty($data)){
        return $this->query($table);
      }

      if(is_string($data)){
        $key_value_string = $data;
      }elseif(is_array($data)){
        if(!is_assoc_array($data)){
          return FALSE;
        }
        $key_value_pairs = array();
        foreach($data as $k => $v){
          $key_value_pairs[] = "{$k}='{$v}'";
        }
        $key_value_string = implode(', ', $key_value_pairs);
      }
      if(empty($key_value_string)){
        return FALSE;
      }

      if(is_string($condition)){
        $condition_string = $condition;
      }elseif(is_array($condition)){
        $conditions = array();
        if(array_depth($condition) == 1){
          $condition = array(0 => $condition);
        }
        foreach($condition as $v){
          switch ($v[1]) {
            case 'in':
              $vals = implode("', '", $v[2]);
              $conditions[] = "{$v[0]} IN ('{$vals}')";
              break;
            case 'like':
              $conditions[] = "{$v[0]} LIKE '%{$v[2]}%'";
              break;
            case 'find_in_set':
              $conditions[] = "FIND_IN_SET({$v[0]}, {$v[2]})>0";
              break;
            default :
              $conditions[] = "{$v[0]}{$v[1]}'{$v[2]}'";
          }
        }
        $condition_string = implode(' AND ', $conditions);
      }

      $SQL = "UPDATE {$table} SET {$key_value_string}";
      if(!empty($condition_string)){
        $SQL .= " WHERE {$condition_string}";
      }
      return $this->query($SQL);
    }

    public function get_all($SQL)
    {
      if($rs = $this->query($SQL)){
        if(is_object($rs)){
          $result = array();
          while($row = mysqli_fetch_assoc($rs)){
            $row = mb_mysqli_row($row, $this);
            $result[] = $row;
          }
          mysqli_free_result($rs);

          return $result;
        }else{
          return TRUE;
        }
      }
      return FALSE;
    }

    public function get_one($SQL)
    {
      if(stripos($SQL, ' LIMIT ') === FALSE){
        $SQL .= ' LIMIT 1';
      }
      if($rs = $this->query($SQL)){
       if(is_object($rs)){
          $result = NULL;
          if($row = mysqli_fetch_assoc($rs)){
            $result = mb_mysqli_row($row, $this);
          }
          mysqli_free_result($rs);

          return $result;
       }else{
         return TRUE;
       }
      }
      return FALSE;
    }

    public function database()
    {
      return $this->link ? $this->database : NULL;
    }

    public function errno()
    {
      return $this->link ? mysqli_errno($this->link) : NULL;
    }

    public function error()
    {
      return $this->link ? mysqli_error($this->link) : NULL;
    }

    public function affected_rows()
    {
      return $this->link ? mysqli_affected_rows($this->link) : FALSE;
    }

    public function updated()
    {
      return $this->link ? mysqli_affected_rows($this->link) > 0 : FALSE;
    }

    public function insert_id()
    {
      return $this->link ? mysqli_insert_id($this->link) : FALSE;
    }

    public function escape_array($x = null)
    {
      if(is_array($x)){
        foreach($x as $k => $v) {
          $x[$k] = $this->escape_array($v); //recursive
        }
      }elseif(is_string($x)){
        $x = mysqli_real_escape_string($this->link, $x);
      }
      return $x;
    }

    public function table_exists($table)
    {
      $table = explode('.', $table);
      $tables = $this->get_all(empty($table[1]) ? "SHOW TABLES LIKE '{$table[0]}'" : "SHOW TABLES FROM {$table[0]} LIKE '{$table[1]}'");
      return count($tables) > 0;
    }
  }

  function mb_mysqli_row($row, $db)
  {
    if($db->codepage == 'utf8') return $row;
    if(is_array($row)) foreach($row as $k => $v){
      $row[$k] = @iconv('GBK', 'UTF-8', $v);
    }
    return $row;
  }

  function conndb($param, $debug = false)
  {
    empty($param['host']) && $param['host'] = 'localhost';
    empty($param['user']) && $param['user'] = 'root';
    empty($param['pass']) && $param['pass'] = '';
    empty($param['database']) && $param['database'] = '';
    empty($param['codepage']) && $param['codepage'] = NULL;
    return new db_mysql($param['host'], $param['user'], $param['pass'], $param['database'], $param['codepage'], $debug);
  }

  function mysqli_escape_array($link, $x=null)
  {
    if(!empty($link)){
      if(is_array($x)){
        foreach($x as $k => $v) {
          $x[$k] = mysqli_escape_array($link, $v); //recursive
        }
      }elseif(is_string($x)){
        $x = mysqli_real_escape_string($link, $x);
      }
    }
    return $x;
  }

  function array_sum_ext($array, $params = array('d' => 'x', 'k' => 'xxx'), $exclusions = array())
  {
    if(!empty($array)) {
      $sum = 0;
      if($params['d'] == 'x') {
        $keys = array_keys($array);
        for($x = 0; $x < count($keys); $x++) {
          if(in_array($keys[$x], $exclusions)) continue;
          $sum += $array[$keys[$x]];
        }
        return $sum;
      } elseif($params['d'] == 'y') {
        $keys = array_keys($array);
        $k = is_array($params['k']) ? $params['k'] : explode(',', $params['k']);
        $l = $k[count($k) - 1];
        for($x = 0; $x < count($keys); $x++) {
          if(!in_array($keys[$x], $exclusions)){
            $v = $array[$keys[$x]];
            foreach($k as $w){
              if(!array_key_exists($w, $v)) continue 2;
              $v = $v[$w];
            }
            $sum += array_sum_multi_dimesion($v);
          }
        }
        return $sum;
      } else return 0;
    } else return 0;
  }

  function array_sum_multi_dimesion($a)
  {
    if(!is_array($a)) return $a;
    $s = 0;
    foreach($a as $v){
      $s += is_array($v) ? array_sum_multi_dimesion($v) : $v;
    }
    return $s;
  }

  function array_tolower($str){
    if(is_array($str)){
      return array_map('array_tolower', $str);
    }

    return strtolower($str);
  }

  function serial_next($last_serial)
  {
    $prefix = '';
    $serial = $last_serial;
    $pos = 0;
    while(!is_numeric($serial)){
      $pos ++;
      $prefix = substr($last_serial, 0, $pos);
      $serial = substr($last_serial, $pos);
    }
    return $prefix . ($serial + 1);
  }

  function sc($number = 0, $int_unit = '元', $is_round = TRUE, $is_extra_zero = FALSE)
  {
    $prefix = '';
    if($number < 0){
      $prefix = '（负数）';
      $number = -1 * $number;
    }
    $parts = explode('.', $number . '', 2);

    $int = isset($parts[0]) ? strval($parts[0]) : '0';
    $dec = isset($parts[1]) ? strval($parts[1]) : '';

    $dec_len = strlen($dec);
    if (isset($parts[1]) && $dec_len > 2) {
      $dec = $is_round ? substr(strrchr(strval(round(floatval("0.".$dec), 2)), '.'), 1) : substr($parts[1], 0, 2);
    }
    $dec = rtrim($dec, '0');

    $chs = array('0','壹','贰','叁','肆','伍','陆','柒','捌','玖');
    $uni = array('','拾','佰','仟');
    $dec_uni = array('角', '分');
    $exp = array('', '万');
    $res = (empty($int) && empty($dec)) ? '零' : '';

    for($i = strlen($int) - 1, $k = 0; $i >= 0; $k++) {
      $str = '';

      for($j = 0; $j < 4 && $i >= 0; $j++, $i--) {
        $u = $int[$i] > 0 ? $uni[$j] : '';
        $str = $chs[$int[$i]] . $u . $str;
      }

      $str = rtrim($str, '0');
      $str = preg_replace("/0+/", "零", $str);
      if(!isset($exp[$k])) {
          $exp[$k] = $exp[$k - 2] . '亿';
      }
      $u2 = $str != '' ? $exp[$k] : '';
      $res = $str . $u2 . $res;
    }


    if(!empty($dec)) {
      if(!empty($res)){
        $res .= $int_unit;

        if ($is_extra_zero) {
          if (substr($int, -1) === '0') {
            $res .= '零';
          }
        }
      }

      for($i = 0, $cnt = strlen($dec); $i < $cnt; $i++) {
        $u = $dec[$i] > 0 ? $dec_uni[$i] : '';
        $res .= $chs[$dec[$i]] . $u;
      }
      $res = rtrim($res, '0');
      $res = preg_replace("/0+/", "零", $res);
      if(strlen($dec) < 2)
        $res .= '整';
    } else {
      $res .= $int_unit . '整';
    }
    return $prefix . $res;
  }

  function file_ext_by_name($fStr){/*取得文件的扩展名并返回*/
    $retval = '';
    $pt = strrpos($fStr, '.');/*取得最后一个句号(.)在文件名中的位置*/
    if($pt){
      $retval = substr($fStr, $pt + 1, strlen($fStr) - $pt);/*最后一个句号后面就是扩展名*/
    }
    return(strtolower($retval));
  }

  function json_encode_ex($value, $options = 0)
  {
    if(version_compare(PHP_VERSION,'5.4.0','<')){
      $str = json_encode($value, $options);
      $str = preg_replace_callback("#\\\u([0-9a-f]{4})#i",
        function($matchs){
          return  iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
        }, $str
      );
      return $str;
    }else{
      return json_encode($value, $options + JSON_UNESCAPED_UNICODE);
    }
  }

  function date_yearspast($startDate, $endDate = 'now')
  {
    $startDate = strtotime($startDate);
    $endDate = strtotime($endDate);

    if($startDate === false || $endDate === false || $startDate > $endDate)
      return '(未知)';

    $years = date('Y', $endDate) - date('Y', $startDate);

    $endMonth = date('n', $endDate);
    $startMonth = date('n', $startDate);

    // Calculate months
    $endDay = date('j', $endDate);
    $startDay = date('j', $startDate);

    $months = $endMonth - $startMonth;
    $days = $endDay - $startDay;
    if($days < 0) $months --;
    if ($months < 0)  $years --;

    if ($years < 0) return '(未知)';

    return $years;
  }

  function date_dayspast($startDate, $endDate = 'now')
  {
    $startDate = strtotime($startDate);
    $endDate = strtotime($endDate);

    if($startDate === false || $endDate === false) return false;

    $days_past = ($endDate - $startDate) / 86400;
    return $days_past > 0 ? floor($days_past) : ceil($days_past);
  }

  function date_in_id($id)
  {
    switch(strlen($id)){
      case 15:
        return '19' . substr($id, 6, 2) . '-' . substr($id, 8, 2) . '-' . substr($id, 10, 2);
      case 18:
        return substr($id, 6, 4) . '-' . substr($id, 10, 2) . '-' . substr($id, 12, 2);
      default:
        return '0000-00-00';
    }
  }

  function number_format_ex($number, $decimals = 0, $dec_point = '.', $thousands_sep = ',')
  {
    $number = floatval($number);
    return empty($number) ? '' : number_format($number, $decimals, $dec_point, $thousands_sep);
  }

  function strip_no_printable($str){
    if(is_array($str)){
      return array_map('strip_no_printable', $str);
    }
    $search = array("\r\n", "\r", "\n", "\t", ' ');
    return strip_tags(str_replace($search, '', $str));
  }

  function array_exchange($array){
    array_unshift($array, null);
    return call_user_func_array('array_map', $array);
  }

  function array_expand($array){
    return (array_exchange(array_exchange($array)));
  }

  function merge_title_cells($worksheet, &$export_title, $index = 0, $exchanged = FALSE)
  {
    if(is_array($export_title[0])){
      if(empty($exchanged)){
        $export_title_clone = $export_title;

        array_unshift($export_title_clone, null);
        $export_title_clone = call_user_func_array('array_map', $export_title_clone);

        merge_title_cells($worksheet, $export_title_clone, 0, TRUE);
      }else{
        foreach($export_title as $row_index => &$row){
          merge_title_cells($worksheet, $row, $row_index, TRUE);
        }

        array_unshift($export_title, null);
        $export_title = call_user_func_array('array_map', $export_title);

        foreach($export_title as $row_index => $row){
          merge_title_cells($worksheet, $row, $row_index, FALSE);
        }
      }
    }elseif($exchanged){
      $export_title = array_values($export_title);
      $c = PHPExcel_Cell::stringFromColumnIndex($index);

      $e = -1;
      while(empty($export_title[++ $e]));
      for(; $e < count($export_title) - 1;){
        $s = ++ $e;
        if($export_title[$e] != ''){
          continue;
        }
        while($e < count($export_title) && empty($export_title[$e])){
          $export_title[$e] = ' ';
          $e ++;
        };

        $worksheet->mergeCells("{$c}{$s}:{$c}{$e}");
      }
    }else{
      $export_title = array_values($export_title);
      $r = $index + 1;

      $k = -1;
      while(empty($export_title[++ $k]));
      for(; $k < count($export_title) - 1;){
        $s = PHPExcel_Cell::stringFromColumnIndex($k ++);
        if($export_title[$k] != ''){
          continue;
        }
        while($k < count($export_title) && empty($export_title[$k])){
          $k ++;
        }
        $e = PHPExcel_Cell::stringFromColumnIndex($k - 1);

        $worksheet->mergeCells("{$s}{$r}:{$e}{$r}");
      }
    }
  }

  function mobile_mask($mobile)
  {
    $s = str_split($mobile, 1);

    $s = array_fill(3, count($s) - 7, '*') + $s;
    ksort($s);

    return implode('', $s);
  }

  function account_mask($account)
  {
    $s = str_split($account, 1);

    $s = array_fill(4, count($s) - 8, '*') + $s;
    ksort($s);

    return implode('', $s);
  }

  function idcard_mask($id)
  {
    if(empty($id)) return '';
    if(strlen($id) <= 10) return $id;

    $s = str_split($id,1);

    $s = array_fill(6, count($s) - 10, '*') + $s;
    ksort($s);

    return implode('', $s);
  }

  function valid_pass($s)
  {
    $r1 = '/[A-Z]/';  //uppercase
    $r2 = '/[a-z]/';  //lowercase
    $r3 = '/[0-9]/';  //numbers
    $r4 = '/[~!@#$%^&*()\-_=+{};:<,.>?]/';  // special char

    if(strlen($s) < 8) {
      return 0;
    }

    $r = 0;
    if(preg_match_all($r1, $s, $o) > 0) {
      $r ++;
    }

    if(preg_match_all($r2, $s, $o) > 0) {
      $r ++;
    }

    if(preg_match_all($r3, $s, $o) > 0) {
      $r ++;
    }

    if(preg_match_all($r4, $s, $o) > 0) {
      $r ++;
    }

    return $r;
  }

  // $_syslog = 'nhjr_syslog';
  // function nhjr_syslog($syslog_info, $db = NULL)
  // {
  //   if($_SESSION['oid'] == '-1'){ return FALSE; }
  //   if(empty($db)){ $db = $GLOBALS['db']; }
  //   if($db->table_exists($GLOBALS['_syslog']) == FALSE){
  //     return FALSE;
  //   }
  //   $_syslog['syslog_id'] = empty($syslog_info['uid']) ? (empty($_SESSION['uid']) ? '0' : $_SESSION['uid']) : $syslog_info['uid'];
  //   $_syslog['syslog_name'] = empty($_SESSION['czy_xm']) ? '' : $_SESSION['czy_xm'];
  //   $_syslog['syslog_ip'] = $_SERVER['REMOTE_ADDR'];
  //   $_syslog['syslog_url'] = $_SERVER['SCRIPT_NAME'];

  //   if(empty($syslog_info['request'])){
  //     foreach($_GET as $k => $v){
  //       if($v == ''){
  //         $_syslog['syslog_request'] = $k;
  //         break;
  //       }
  //     }
  //   }else{
  //     $_syslog['syslog_request'] = $syslog_info['request'];
  //     unset($syslog_info['request']);
  //   }

  //在已经存在的系统上学习、改造
  // $_syslog = 'xtjc_syslog';
  // function xtjc_syslog($syslog_info, $db = NULL)
  // {
  //   if($_SESSION['oid'] == '-1'){ return FALSE; }
  //   if(empty($db)){ $db = $GLOBALS['db']; }
  //   if($db->table_exists($GLOBALS['_syslog']) == FALSE){
  //     return FALSE;
  //   }
  //   $_syslog['syslog_id'] = empty($syslog_info['uid']) ? (empty($_SESSION['uid']) ? '0' : $_SESSION['uid']) : $syslog_info['uid'];
  //   $_syslog['syslog_name'] = empty($_SESSION['czy_xm']) ? '' : $_SESSION['czy_xm'];
  //   $_syslog['syslog_ip'] = $_SERVER['REMOTE_ADDR'];
  //   $_syslog['syslog_url'] = $_SERVER['SCRIPT_NAME'];

  //   if(empty($syslog_info['request'])){
  //     foreach($_GET as $k => $v){
  //       if($v == ''){
  //         $_syslog['syslog_request'] = $k;
  //         break;
  //       }
  //     }
  //   }else{
  //     $_syslog['syslog_request'] = $syslog_info['request'];
  //     unset($syslog_info['request']);
  //   }
  // }
  //此函数与上一个注释掉的函数一样，目的是生成系统日志

  function https_request($url, $data = null)
  {
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Connection: Keep-Alive'
      ));
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
      if (!empty($data)){
          curl_setopt($curl, CURLOPT_POST, 1);
          curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
      }
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      $output = curl_exec($curl);
      curl_close($curl);
      return $output;
  }

  /**
   * 判断数组是否为索引数组
   */
  function is_indexed_array($arr)
  {
    if (is_array($arr)) {
      return count(array_filter(array_keys($arr), 'is_string')) === 0;
    }
    return false;
  }
  /**
   * 判断数组是否为连续的索引数组
   */
  function is_continuous_indexed_array($arr)
  {
    if (is_array($arr)) {
      $keys = array_keys($arr);
      return $keys === array_keys($keys);
    }
    return false;
  }
  /**
   * 判断数组是否为关联数组
   */
  function is_assoc_array($arr)
  {
    if (is_array($arr)) {
      return count(array_filter(array_keys($arr), 'is_string')) === count($arr);
    }
    return false;
  }
  /**
   * 判断数组是否为混合数组
   */
  function is_mixed_array($arr)
  {
    if (is_array($arr)) {
      $count = count(array_filter(array_keys($arr), 'is_string'));
      return $count !== 0 && $count !== count($arr);
    }
    return false;
  }

  function array_depth($array) {
    if(!is_array($array)) return 0;
    $max_depth = 1;
    foreach ($array as $value) {
      if (is_array($value)) {
        $depth = array_depth($value) + 1;

        $max_depth = max($max_depth, $depth);
      }
    }
    return $max_depth;
  }

  if(empty($debug_mode)){
    $is_debug = file_exists(SQL_LOG_DIR) && is_dir(SQL_LOG_DIR);
  }else{
    if(file_exists(SQL_LOG_DIR)){
      $is_debug = is_dir(SQL_LOG_DIR);
    }else{
      $is_debug = mkdir(SQL_LOG_DIR,0777);
    }
  }

  if(php_sapi_name() === 'cli' || session_id() === ''){
    // 命令行模式，或SESSION未开启(不依赖于会话)的时候不检测超时
  }else{
    if(isset($_SESSION['uid']) && $_SESSION['uid'] == '-1'){
      $_SESSION['expiretime'] = time() + 900;
    }else{
      if($token = (empty($_COOKIE['token']) ? '' : $_COOKIE['token'])){
        $request = json_encode(array('method' => 'heartbeat', 'token' => $token));
        $response_text = https_request('https://login.shanbansyh.com.cn/synchronous.php', $request);
        $response = json_decode($response_text, TRUE);

        if(empty($response) || !isset($response['code']) || $response['code'] != 0){
          session_unset();
          if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
              $params["path"], $params["domain"],
              $params["secure"], $params["httponly"]
            );
          }
          session_destroy();
          setcookie('token', '', time() - 42000, '/');

          echo <<<EOT
<script type="text/javascript">
  alert("会话已超时，请重新登录后继续操作。");
  top.location.reload();\n
EOT;
          exit('</script>');
        }else{
          $_SESSION['expiretime'] = time() + 900; // 刷新时间戳
        }
      }
    }
  }

  $config = __DIR__ .  DIRECTORY_SEPARATOR . basename(__FILE__, '.php') . '.cfg';
  if(file_exists($config)){
    $param = parse_ini_file($config);
  }else{
    $param = array(
      'host' => 'localhost',
      'database' => 'gzdemo',
      'user' => 'gzdemo',
      'pass' => '8fj5kq7b',
      'codepage' => ''
    );
  }
  $db = new db_mysql($param['host'], $param['user'], $param['pass'], $param['database'], $param['codepage'], $is_debug);
  if(empty($db->link)){
    die("连接数据库失败，失败原因：{$db->error}");
  }
  // if(!isset($_SESSION['CFG'])){
  //   $_SESSION['CFG'] = $db->get_one("SELECT * FROM gzglnew.gz_config");
  // }
  // $CFG = $_SESSION['CFG'];
?>
